package cn.ivast.recyclerviewtest.decoration;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

/**
 * Created by hcs on 2018/11/25.
 */
public class StickyDecoration extends RecyclerView.ItemDecoration {

    private final Paint paint;
    private int mHeight = 140;
    private Paint mTextPaint;
    GroupListener listener;

    public void setListener(GroupListener listener) {
        this.listener = listener;
    }

    public StickyDecoration() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = parent.getChildAdapterPosition(view);
        String groupId = listener.getGroupName(position);
        if (groupId == null) {
            return;
        }
        //为第一个是标题的item预留空间
        if (position == 0 || isFirstInGroup(position)) {
            outRect.top = mHeight;
        }

        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setColor(Color.parseColor("#ffffff"));
        mTextPaint.setTextSize(50f);
    }

    /**
     * 通过该方法，在Canvas上绘制内容,在Item之后调用。(画的内容会覆盖在item的上层)
     * @param c
     * @param parent
     * @param state
     */
    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        int itemCount = state.getItemCount();
        int childCount = parent.getChildCount();
        int left = parent.getLeft() + parent.getPaddingLeft();
        int right = parent.getRight() - parent.getPaddingRight();
        //标记上一个item对应的Group
        String preGroupName;
        //当前item对应的Group
        String currentGroupName = null;
        for (int i = 0; i < childCount; i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);
            preGroupName = currentGroupName;
            currentGroupName = listener.getGroupName(position);
            if (currentGroupName == null || TextUtils.equals(currentGroupName, preGroupName)) {
                continue;
            }
            int viewBottom = view.getBottom();
            //top决定当前顶部第一个悬浮Group的位置
            //根据当前Item的位置确定绘制分组的位置。top将在mGroupHeight和view.getTop()中取最大值，也就是说top将不会小于mGroupHeight，这样就能实现吸顶效果。
            float top = Math.max(mHeight, view.getTop());
            if (position + 1 < itemCount) {
                //获取下个GroupName
                String nextGroupName = listener.getGroupName(position + 1);
                //下一组的第一个View接近头部
                //当下个分组的顶部（当前Item的底部viewBottom可近似认为下个Item的顶部）距离RecyclerView顶部小于top时，偏移当前分组位置。实现下一组上滑时候，当前分组上移；上一组下滑的时候，当前分组下移。
                if (!currentGroupName.equals(nextGroupName) && viewBottom < top) {
                    top = viewBottom;
                }
            }
            //根据top绘制group
            c.drawRect(left, top - mHeight, right, top, paint);
            Paint.FontMetrics fm = mTextPaint.getFontMetrics();
            //文字竖直居中显示
            float baseLine = top - (mHeight - (fm.bottom - fm.top)) / 2 - fm.bottom;
            c.drawText(currentGroupName, left + 10, baseLine, mTextPaint);

        }
    }

    /**
     * 判断是不是组中的第一个位置,根据前一个组名，判断当前是否为新的组
     * @param pos
     * @return
     */
    private boolean isFirstInGroup(int pos) {
        if (pos == 0) {
            return true;
        } else {
            String prevGroupId = listener.getGroupName(pos - 1);
            String groupId = listener.getGroupName(pos);
            return !TextUtils.equals(prevGroupId, groupId);
        }
    }


    public interface GroupListener {
        String getGroupName(int position);
    }


}
